<?php
class theme{
	var $dir, $name, $items, $cache, $caching, $errno;
	
	function assign($item, $value=null){
		if(is_array($item)){
			foreach($item as $key => $val)
				$this->items[$key] = $val;;
		}else{
			$this->items[$item] = $value;
		}
	}
	
	function import($node){
		if($node == '') return false;
		if(is_file(ROOTDIR .'/models/'. $node .'.mod.php')){
			require_once(ROOTDIR .'/models/'. $node .'.mod.php');
			$model = 'mod_'. $node;
			if(class_exists($model)) return new $model();
		}
		return false;
	}
	
	function exists($node){
		return is_file($this->themedir() .'/'. $node .'.tpl.php');
	}
	
	function caching($time){
		if(!is_numeric($time)){
			$unit = substr($time, -1);
			$time = floatval(substr($time, 0, -1));
			switch($unit){
				case 'h': $time *= 3600; break;
				case 'd': $time *= 86400; break;
				case 'm': $time *= 2592000; break;
				case 'y': $time *= 31536000; break;
				default : $time *= 86400;
			}
		}
		$this->caching = $time;
	}
	
	function display($node, $tpl=''){
		@header('content-type:text/html; charset=utf-8');
		if(is_file($this->themedir() . $tpl .'.tpl.php')){
			$this->theme = $this->themedir() . $tpl .'.tpl.php';
		}else{
			$this->theme = $this->themedir() . $node .'.tpl.php';
		}
		if(is_file($this->theme) === true){
			$skindir = $this->themedir(false);
			extract($this->items); require($this->theme);
			$this->errno = 0; exit;
		}else die('Cannot find template file: '. $this->theme);
	}
	
	function querystr($tag=''){
		$qstr = $_SERVER['REQUEST_URI'];
		if($tag != '') $qstr = $tag;
		$this->assign('querystr', $qstr);
		return $qstr;
	}
	
	function themedir($real=true){
		$dir = $this->dir;
		if(!$real) $dir = str_replace(ROOTDIR .'/', '', $this->dir);
		return $dir . $this->name .'/';
	}
	
	function __construct($tag=''){
		ob_start();
		
		defined('ROOTDIR') or die('Undefined ROOTDIR!');
		
		$this->dir = ROOTDIR .'/themes/';
		$this->name = 'default';
		$this->items = array();
		$this->caching = 0;
		$this->errno = 1;

		$path = ROOTDIR .'/caches/html/';
		if(!is_dir($path)) mkdir($path);

		// Obtain page caching
		$this->cache = $path . md5($this->querystr($tag)) .'.cache';
		if(is_file($this->cache)){
			$data = file_get_contents($this->cache);
			if(intval(substr($data, 0, 10)) > time()){
				@header('content-type:text/html;charset=utf-8');
				exit(substr($data, 10));
			}
		}
	}
	
	function __destruct(){
		// Storage the page caching
		if($this->errno == 0 && $this->caching > 0){
			$time = time() + $this->caching;
			file_put_contents($this->cache, $time . ob_get_flush());
		}
	}
}
?>
